<template>
  <Modal
    cancelText="取消"
    okText="确认"
    v-model:visible="visible"
    @ok="handleSubmit"
    width="800px"
    title="编辑个人信息"
  >
    <Form class="p-4 xl:text-left" ref="formRef" :model="formState">
      <FormItem
        label="登录账户"
        name="userName"
        :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
      >
        <Input v-model:value="formState.userName" placeholder="登录账户" disabled />
      </FormItem>
      <FormItem
        label="姓名"
        name="name"
        :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
      >
        <Input v-model:value="formState.name" placeholder="姓名" />
      </FormItem>
      <FormItem
        label="手机号"
        :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
        name="phone"
        :rules="[
          {
            required: phoneChecked,
            message: '手机号不可为空',
          },
          {
            pattern: phoneRule,
            message: '请输入正确的手机号',
          },
        ]"
      >
        <div class="md:flex">
          <Input v-model:value="formState.phone" placeholder="手机号" :disabled="!phoneChecked" />
          <FormItem style="height: 10px">
            <Switch
              size="large"
              v-model:checked="phoneChecked"
              checked-children="I"
              un-checked-children="O"
              class="mx-3"
            ></Switch>
          </FormItem>
        </div>
      </FormItem>

      <FormItem
        label="邮箱"
        name="email"
        :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
        :rules="[
          {
            required: mailChecked,
            message: '邮箱不可为空',
          },
          {
            pattern: emailRule,
            message: '请输入正确的邮箱',
          },
        ]"
      >
        <div class="md:flex">
          <Input v-model:value="formState.email" placeholder="邮箱" :disabled="!mailChecked" />
          <FormItem style="height: 10px">
            <Switch
              size="large"
              v-model:checked="mailChecked"
              checked-children="I"
              un-checked-children="O"
              class="mx-3"
            ></Switch>
          </FormItem>
        </div>
      </FormItem>
      <FormItem
        label="原密码"
        name="originalPassword"
        :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
        :rules="[
          { required: true, message: '想要修改信息,原密码必填' },
          {
            pattern:
              '^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,18}$',
            message: '请输入正确的密码',
          },
        ]"
      >
        <InputPassword v-model:value="formState.originalPassword" placeholder="原密码" />
      </FormItem>
      <FormItem
        label="新密码"
        name="newPassword"
        :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
        :rules="[
          {
            pattern:
              '^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,18}$',
            message: '请输入正确的密码',
          },
        ]"
      >
        <InputPassword v-model:value="formState.newPassword" placeholder="新密码" />
      </FormItem>
      <FormItem
        label="确认密码"
        name="repeatPassword"
        :rules="[{ validator: validatePass, trigger: 'change' }]"
        :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
      >
        <InputPassword v-model:value="formState.repeatPassword" placeholder="确认密码" />
      </FormItem>
      <FormItem
        label="验证码"
        name="verificationCode"
        :wrapperCol="{ xs: { span: 24 }, sm: { span: 19 } }"
        :labelCol="{ xs: { span: 24 }, sm: { span: 5 } }"
        :rules="[
          {
            required: true,
            message: '请输入验证码',
          },
        ]"
      >
        <div class="md:flex">
          <VerificationCode
            buttonName="发送"
            :selectOptions="selectOptions"
            :limitTimer="50"
            :buttonFunction="sendVerificationCodeHandler"
            ref="verificationCodeRef"
            @code="codeHandler"
          />
        </div>
      </FormItem>
    </Form>
  </Modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { Form, Input, InputPassword, Switch, Modal } from 'ant-design-vue';
import { useUserStoreWithout } from '/@/store/modules/user';
import VerificationCode from '/@/components/VerificationCode/VerificationCode.vue';
import { sendVerificationCode } from '/@/api/sys/userInfo';
import { Rule } from 'ant-design-vue/lib/form';
import { useMessage } from '/@/hooks/web/useMessage';
import { updateInfo } from '/@/api/sys/userInfo';

interface FormState {
  userName: string;
  name: string;
  phone: string;
  email: string;
  originalPassword: string;
  newPassword: string;
  repeatPassword: string;
  verificationCode: string;
}

let formState = ref<FormState>({
  userName: '',
  name: '',
  phone: '',
  email: '',
  originalPassword: '',
  newPassword: '',
  repeatPassword: '',
  verificationCode: '',
});

const { createMessage } = useMessage();
const userStore = useUserStoreWithout();
const FormItem = Form.Item;
const phoneChecked = ref(false);
const mailChecked = ref(false);
const phoneRule = ref('');
const emailRule = ref('');
const tempPhone = ref();
const tempEmail = ref();
const visible = ref(false);

const openModal = () => {
  visible.value = true;
};
const closeModal = () => {
  visible.value = false;
};

const formRef = ref();

watch(
  () => phoneChecked.value,
  async () => {
    if (phoneChecked.value) {
      phoneRule.value = '^0?(13|14|15|17|18|19)[0-9]{9}$';
      tempPhone.value = formState.value.phone;
      formState.value.phone = undefined;
    } else {
      phoneRule.value = await undefined;
      formRef.value.resetFields('phone');
      formState.value.phone = await tempPhone.value;
    }
  }
);

watch(
  () => mailChecked.value,
  async () => {
    if (mailChecked.value) {
      emailRule.value = '^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$';
      tempEmail.value = formState.value.email;
      formState.value.email = '';
    } else {
      emailRule.value = await undefined;
      formRef.value.resetFields('email');
      formState.value.email = await tempEmail.value;
    }
  }
);

const emits = defineEmits(['success']);
const verificationCodeRef = ref('verificationCodeRef');

const selectOptions = ref([
  {
    label: '手机',
    value: 'PHONE',
  },
  {
    label: '邮箱',
    value: 'EMAIL',
  },
]);

const setFormValue = (value) => {
  formState.value = { ...value };
};

const handleSubmit = async () => {
  formState.value.verificationCode = verificationCodeRef.value.getVerificationCode();
  formState.value.isUpdatePhone = phoneChecked.value;
  formState.value.isUpdateEmail = mailChecked.value;
  formState.value.userId = userStore.getUserInfo.userId;
  await formRef.value.validate();
  await updateInfo(formState.value);
  emits('success');
  createMessage.success('修改用户信息成功');
  closeModal();
};

let validatePass = async (_rule: Rule, value: string) => {
  if (value && value !== formState.value.newPassword) {
    return Promise.reject(new Error('请输入相同密码'));
  } else {
    return Promise.resolve();
  }
};

const sendVerificationCodeHandler = (options: any) => {
  sendVerificationCode({ type: options, pageType: 'PERSON_INFO', userId: userStore.getUserInfo.userId });
};

const codeHandler = (code: string) => {
  if (code !== '') {
    formRef.value.clearValidate(['verificationCode']);
  }
};

defineExpose({ openModal, closeModal, setFormValue });
</script>

<style lang="less" scoped>
.user-form {
  width: 400px;
  border-radius: 5px;
  padding: 20px 0 0 0;
  background: white;
  backdrop-filter: blur(3px);
  animation: action 0.6s ease-out 0s backwards;

  .ant-form {
    width: 400px;
    font-size: 12px;
    color: dimgray;
    margin-bottom: 5px;
  }
}

@keyframes action {
  0% {
    transform: translate(-20px);
    opacity: 0;
  }

  50% {
    transform: translate();
    opacity: 0.5;
  }

  100% {
    transform: translate(0);
    opacity: 1;
  }
}
</style>
